import inspect


def key_maker(key_pattern, func):
    arg_names, varargs, varkw, defaults = inspect.getargspec(func)
    args = dict(zip(arg_names[-len(defaults):], defaults)) if defaults else {}
    # if callable(key_pattern):
    #    names = inspect.getargspec(key_pattern)[0]

    if key_pattern is None:
        key_pattern = []
        if arg_names and arg_names[0] in ('cls', 'self'):
            a = arg_names[1:]
        else:
            a = arg_names

        for i in a:
            key_pattern.append("{%s}" % i)
        key_pattern = "-".join(key_pattern)

    key_pattern = func.__module__.replace(".async", '').replace(
        '.sync', ''
    ) + "." + func.__qualname__ + ":" + key_pattern

    # print(key_pattern)
    def gen_key(*a, **kw):
        aa = args.copy()
        aa.update(zip(arg_names, a))
        aa.update(kw)
        # if callable(key_pattern):
        #    key = key_pattern(*[aa[n] for n in names])
        # else:
        key = key_pattern.format(**aa)
        # print(key)
        return key  # and key.replace(' ','_'), aa

    return gen_key
